package com.saver.modules.sys.controller;

import com.saver.common.db.JdbcTool;
import com.saver.common.utils.R;
import com.saver.modules.sys.dao.SysRoleDao;
import com.saver.modules.sys.entity.SysRoleEntity;
import com.saver.modules.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author yuxiaolong
 * @email 1005471232@qq.com
 * @date 2018年08月25日 下午7:08
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private JdbcTool jdbcTool;

    /**
     * 所有角色
     *
     * @return
     */
    @GetMapping("/all")
    public R all() {
        Long userId = getUserId();
        if (userId == 1) {
            return R.ok().put("roles", sysRoleDao.findAll());
        }
        Set<Long> roleIds = getUser().getRoleIds();
        Iterator<Long> iterator = roleIds.iterator();
        String s = "";
        while (iterator.hasNext()) {
            s = s + iterator.next() + ",";
        }
        if (s.length() > 0) {
            s = s.substring(0, s.length() - 1);
        }
        List<Map<String, Object>> list = jdbcTool.list("select * from sys_role where role_id in(" + s + ") order by role_id asc");
        return R.ok().put("roles", list);
    }

    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        return sysRoleService.queryPage(params);
    }

    @GetMapping("/info/{roleId}")
    public R info(@PathVariable("roleId") Long roleId) {
        return sysRoleService.info(roleId);
    }

    @PostMapping("/save")
    public R save(@RequestBody SysRoleEntity sysRoleEntity) {
        return sysRoleService.save(sysRoleEntity);
    }

    @PostMapping("/delete")
    public R delete(@RequestBody Integer roleId) {
        return sysRoleService.delete(new Long(roleId));
    }

}
